package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.basic.web.repository.BusinessRepository;
import com.tarena.lbs.basic.web.repository.StoreRepository;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.attach.param.PicUpdateParam;
import com.tarena.lbs.pojo.basic.param.StoreParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.po.StorePO;
import com.tarena.lbs.pojo.basic.query.StoreQuery;
import com.tarena.lbs.pojo.basic.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreService {

    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private StoreRepository storeRepository;
    @Autowired
    private BusinessRepository businessRepository;

    /**
     * 查询店铺分页列表数据
     * @param query
     * @return
     * @throws BusinessException
     */
    public PageResult<StoreVO> storePages(StoreQuery query) throws BusinessException {
        //1.拿到登录认证
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        //2.断言 不存在认证对象 抛异常
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        //3.取角色
        Integer adminId = userPrinciple.getId();//登录用户的id
        Roles roles = userPrinciple.getRole();//登录用户的角色
        //4.如果角色是SHOP 查询businessId 固定商家id lbs_admin
        if (roles==Roles.SHOP){
            AdminPO adminPO = adminRepository.getAdminById(adminId);
            Asserts.isTrue(adminPO==null,new BusinessException("-2","商家信息不存在"));
            query.setBusinessId(adminPO.getBusinessId());//拿到商家id
        }
        //根据上述分支提交结果 封装完整的查询条件 有businessId和没有businessId
        //5.调用分页查询
        PageInfo<StorePO> pageInfo = storeRepository.getstores(query);
        //6.封装pageResult返回
        PageResult<StoreVO> voPages = new PageResult<>();
        voPages.setPageNo(pageInfo.getPageNum());
        voPages.setPageSize(pageInfo.getPageSize());
        voPages.setTotal(pageInfo.getTotal());
        List<StoreVO> vos = null;
        if (CollectionUtils.isNotEmpty(pageInfo.getList())){
            vos = pageInfo.getList().stream().map(po->{
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPages.setObjects(vos);
        return voPages;
    }

    /**
     * 新增店铺
     * @param storeParam
     */
    public void storeSave(StoreParam storeParam) throws BusinessException {
        //1.检查角色是否为SHOP 读取认证对象 判断认证是否成功 判断角色是否相等
        checkRole(Roles.SHOP);
        //2.从入参中拿到店铺绑定的商家id 验证是否合法存在
        Integer businessId = storeParam.getBusinessId();
        BusinessPO bizPO = businessRepository.getBusinessById(businessId);
        Asserts.isTrue(bizPO==null,new BusinessException("-2","商家信息不存在"));
        //3.封装数据 补充属性
        StorePO poParam = storeParam2po(storeParam);
        //4.写入到数据层 写到MySQL和ES
        storeRepository.save(poParam);
        //5.po补充自动生成的id 结合业务定义的图片类型 店铺门店图片List 店铺LOGO url
        // 店铺LOGO 300 店铺图片 400
        bindPicture(storeParam, poParam.getId());

    }

    @DubboReference
    private AttachApi attachApi;
    private void bindPicture(StoreParam param, Integer bizId) {
        List<PicUpdateParam> pictures = new ArrayList<>();
        //封装一个店铺logo
        PicUpdateParam logoParam=new PicUpdateParam();
        logoParam.setBusinessId(bizId);
        logoParam.setBusinessType(300);
        //String logUuid = getFileUuidFromUrl(param.getStoreLogo());
        logoParam.setId(Integer.valueOf(param.getStoreLogo()));
        pictures.add(logoParam);
        //封装一个店铺门店的图片List
        List<PicUpdateParam> storeImages = null;
        storeImages=param.getStoreImagesIds().stream().map(strId->{
            PicUpdateParam storeParam = new PicUpdateParam();
            storeParam.setBusinessId(bizId);
            storeParam.setBusinessType(400);
            storeParam.setId(Integer.valueOf(strId));
            return storeParam;
        }).collect(Collectors.toList());
        pictures.addAll(storeImages);
        attachApi.batchUpdateBusiness(pictures);
    }

//    //从url中截取fileUuid
//    private String getFileUuidFromUrl(String url) {
//        //拿到图片的id或者fileUuid 这里需要在数据库中找到url 截取fileUuid作为绑定入参
//        //http://localhost:9081/static/liencesFileUuid
//        String[] splits = url.split("/");
//        return splits[splits.length-1];
//    }

    private StorePO storeParam2po(StoreParam storeParam) {
        StorePO poParam = new StorePO();
        //能拷贝的大量表单属性先拷贝
        BeanUtils.copyProperties(storeParam,poParam);
        //状态 0正常 1禁用
        poParam.setStoreStatus(0);
        Date now = new Date();
        poParam.setCreateTime(now);
        poParam.setUpdateTime(now);
        poParam.setStoreLatitude(storeParam.getLatitude());
        poParam.setStoreLongitude(storeParam.getLongitude());
        //显示图片的url
        String images="";
        List<String> storeImagesIds = storeParam.getStoreImagesIds();
        if (CollectionUtils.isNotEmpty(storeImagesIds)){
            for (int i = 0; i < storeImagesIds.size(); i++){
                if (i==storeImagesIds.size()-1){
                    //最后一个元素 不需要拼接,
                    images+=storeImagesIds.get(i);
                }else {
                    //不是最后一个元素 需要最后拼接,
                    images+=storeImagesIds.get(i)+",";
                }
            }
        }
        log.info("图片的url:{}",images);
        poParam.setStoreImagesId(images);
        return poParam;
    }

    private void checkRole(Roles roles) throws BusinessException {
        //使用断言,当前登录用户角色是否为管理员,不是则抛出异常
        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        //获取登录用户角色
        Roles loginRole = userPrinciple.getRole();
        Asserts.isTrue(loginRole!=roles,new BusinessException("-2","当前用户无权限"));
        log.info("当前用户角色：{}",loginRole);
    }
}
